

function getLocalData() {
   
    
    var local_goods_array = $.cookie('goods_list');
    if (local_goods_array != undefined) {
        var localData = JSON.parse(local_goods_array);
        return localData;
    }
    return null;
};
function reloadData() {
    $('#comparison').empty();
    var localData = getLocalData();
    if (localData == undefined) return;
    for (var i = 0; i < localData.length; i++) {
        $('#comparison').append('<li class="has_item" id="' + localData[i].productID + '"><dl><a href="/goods-' + localData[i].productID + '.html" target="_blank"><img id="comparison_img" src="' + isImgHttp(localData[i].image) + '" alt=""></a><dt><a href="/goods-' + localData[i].productID + '.html" id="comparison_a" target="_blank">' + localData[i].title + '</a><span id="comparison_txt">' + (localData[i].txt ? localData[i].txt : '') + '</span></dt><dd><span class="price">' + '￥' + localData[i].price + '</span> <span class="removethisdate">删除</span></dd></dl></li>');
    };
};
jQuery(function ($) {
    var user = JSON.parse(localStorage.getItem('user_info')) || {};
    var user_id = user.id;
    var small_price = 0;
    if($('.works_show').length){
        $('.works_show').removeClass('clearfix').addClass('resetInlineBlock') ;
      }
    //点击收藏
    if (!$(this).hasClass('select_collect')) {
        $(document).on('click', '.collect_box', function () {
            if (!user_id) {
                alert('您还没有登录，请先登录！');return;
            }
            //先获取到收藏按钮的是否选中
            var is_select = $(this).find('.collect').hasClass('select_collect');
            $(this).find('.collect').toggleClass('select_collect');

            if (user_id == undefined) return;
            var goods_id = $(this).parents('.works_show_item').attr('data-id');
            var param = {
                "GoodsCollect": {
                    "goods_id": goods_id,
                    "user_id": user_id
                },
                "tag": "GoodsCollect"
            };
            var storeId_param = {
                "GoodsCollect": {
                    "user_id": user_id,
                    "goods_id": goods_id
                }
            };
            send_ajax('post', '/head', storeId_param, function callback(data) {
                if (data.code == 200) {
                    send_ajax('post', data.GoodsCollect.count > 0 ? '/delete' : '/post', param, function callback(data) {
                        if (data.code == 200) {}
                    });
                }
            });
        });
    };
    //点击加入购物车
    $(document).on('click', '.join_car', function () {
        var _this = $(this);
        if($(this).find('i').hasClass('carting')){
            alert('购物车中已存在');
            return;
        }
        var goods_ids = $(this).parents('.works_show_item').attr('data-id');
        if (!user_id) {
            var goodsList = JSON.parse(localStorage.getItem('noUsers')) || [];
            if (goodsList.length) {
                $('.drop_shop_car').show();
                $('.no_shop').hide();
                $('.number').html(goodsList.length);
                for (var k = 0; k < goodsList.length; k++) {
                    if (goodsList[k].id == goods_ids) {
                        alert('购物车中已存在！');
                        return;
                    }
                };
            }else {
                $('.drop_shop_car').hide();
                $('.no_shop').show();
            }
            var goodsIdarr = [];
            goodsIdarr.push(goods_ids);
            var param = {
                "Goods[]": {
                    "Goods": {
                        "id{}": goodsIdarr,
                        "@column": "id,name,goods_price,gift_flag,promotion_flag,deleted_flag,preview_flag,promotion_price",
                        "GoodsImgs": {
                            "goods_id@": "Goods[]/Goods/id"
                        }
                    }
                }
            };
            send_ajax('post', '/get', param, function callback(data) {
                if (data.code == 200 && data['Goods[]']) {
                    var data = data['Goods[]'];
                    var param = {
                        user_id: user_id ? user_id : 0,
                        goodsIdList: data[0].id
                    };
                    send_ajax('get', '/api/goods/status', param, function callback(result) {
                        if (result.code == 200&&result.data) {
                            var result = result.data;
                            if(result[goods_ids] !=undefined){
                                data[0].promotion_flag = result[goods_ids].goodsStatus;
                                data[0].promotion_price = result[goods_ids].price;
                                data[0].goods_price = result[goods_ids].price;
                                data[0].GoodsImgs.thumb = isImgHttp(data[0].GoodsImgs.thumb);
                                data[0].goodsPrice = keepTwoDecimalFull(data[0].goods_price);
                                data[0].promotionprice = keepTwoDecimalFull(data[0].promotion_price);
                                data[0].selected_flag = false;
                                goodsList.push(data[0]);
                                $('.number').html(goodsList.length);
                                localStorage.setItem("noUsers", JSON.stringify(goodsList));
                                isUser();
                                alert('购物车添加成功！');
                            }
                            
                        }
                    });
                };
            });
            isUser();
        } else {
            var data = {
                user_id: user_id,
                goods_ids: [goods_ids],
                type: 1
            };
            send_ajax('post', '/api/cart/add', data, function callback(data) {
                if (data.code == 200) {
                    alert('购物车添加成功');
                    $(_this).find('i').addClass('carting');
                    $(_this).find('i').removeClass('s_cart');
                    $('.drop_shop_car').show();
                    $('.no_shop').hide();
                    var param = {
                        "[]": {
                            "join": "&/Cart/goods_id@,</GoodsImgs/goods_id@",
                            "Goods": {},
                            "count": 0,
                            "Cart": {
                                "goods_id@": "/Goods/id",
                                "user_id": user_id
                            },
                            "GoodsImgs": {
                                "goods_id@": "/Goods/id",
                                "main_flag": 1
                                //加入到购物车
                            }
                        }
                    };
                    //购物详情
                    send_ajax('post', '/get', param, function callback(result) {
                        if (result.code == 200&&result["[]"]) {
                            var data = result["[]"];
                            $('.number').html(data.length);
                            small_car(data);
                        }
                    });
                }
            });
        }
    });
    //点击对比将商品添加到对比栏
    $(document).on('click', '.contrast_box', function () {
        //获取点击的商品信息
        var productID = $(this).parents('.works_show_item').attr('data-id');
        var title = $(this).parents('.works_show_item').attr('data-title');
        var txt = $(this).parents('.works_show_item').attr('data-txt');
        var image = $(this).parents('.works_show_item').find('.works_show_pic').find('img').attr('src');
        var price = $(this).parents('.works_show_item').attr('data-price');
        var goods_obj = {
            productID: productID,
            title: title,
            txt: txt,
            image: image,
            price: price
        };
        $("#compare_box").fadeIn();
        //先判断是否选中，如果选中，取消选中效果，return，如果未选中，正常流程
        if ($(this).find('.contrast').hasClass('contrast_se')) {
            //选中
            $(this).find('.contrast').toggleClass("contrast_se");
            deleteItem(productID);
        } else {
            var goods_list = null;
            var local_goods_array = $.cookie('goods_list');
            if (local_goods_array != undefined) {
                goods_list = JSON.parse(local_goods_array);
            } else {
                goods_list = [];
            }
            if (goods_list.length >= 4) {
                alert('最多只能选择4个商品');
                return;
            }
            for (var i = 0; i < goods_list.length; i++) {
                var obj = goods_list[i];
                if (obj.productID == productID) {
                    alert('不能重复添加商品');
                    return;
                }
            }
            $(this).find('.contrast').toggleClass("contrast_se");
            goods_list.push(goods_obj);
            $.cookie('goods_list', JSON.stringify(goods_list), { path: '/' });
            //数据为goods_list
            reloadData();
        }
    });
    function deleteItem(id) {
        var local_goods_array = $.cookie('goods_list');
        var goods_list = JSON.parse(local_goods_array);
        var temp = [];
        for (var i = 0; i < goods_list.length; i++) {
            var obj = goods_list[i];
            if (obj.productID != id) {
                temp.push(obj);
            }
        }
        $.cookie('goods_list', JSON.stringify(temp), { path: '/' });
        reloadData();
    }
    //点击删除单个商品
    $(document).on('click', '.removethisdate', function () {
        var id = $(this).parents(".has_item").attr('id');
        //for循环，遍历，删除对应id
        deleteItem(id);
        $('[data-id=' + id + ']').find(".contrast").removeClass('contrast_se');
    });
    //对比框中商品小于两个弹框提示
    $('.comparison_button_box').click(function () {
        var localData = getLocalData();
        if (localData.length < 2) {
            alert('当前对比字画少于2幅，请再添加后进行对比！');
        } else {
            window.location.href = '/goods/goods_compare.html';
        }
    });
    //点击清空对比栏
    $('.removealldate').click(function () {
        var localData = getLocalData();
        if (localData == null) {
            return;
        }
        $.removeCookie('goods_list', { path: '/' });
        //寻找已选中的，删除选中效果
        for (var i = 0; i < localData.length; i++) {
            var obj = localData[i];
            $('[data-id=' + obj.productID + ']').find(".contrast").removeClass('contrast_se');
        }
        reloadData();
    });
    //点击隐藏关闭对比栏
    $('.compare_box_title span').click(function () {
        $('#compare_box').fadeOut();
    });
    //小购车
    function small_car(data) {
        var html = "";
        var dataList = [];
        var goodsIdArr=[];
        for (var i = 0; i < data.length; i++) {
            goodsIdArr.push(data[i].Goods.id);

        }
        var param = {
            user_id: id ? id : 0,
            goodsIdList: goodsIdArr.join(',')
        };

        send_ajax('get', '/api/goods/status', param, function callback(res) { 
            if(res.code==200&&res.data){
                var result = res.data;
              for(var i = 0;i<data.length;i++){
                  var a_goods = data[i];
                  var goodsId = a_goods.Goods.id;
                  if(result[goodsId]!= undefined){
                    a_goods.Goods.goods_price = result[goodsId].price;

                  }
                small_price += parseInt(data[i].Goods.goods_price);
                html += '\n                <li class="clearfix">\n                    <div class="shoping_pic">\n                        <a href="/goods-' + data[i].Goods.id + '.html"><img src="' + (data[i].GoodsImgs ? isImgHttp(data[i].GoodsImgs.thumb) : '') + ('" alt=""></a>\n                    </div>\n                    <div class="pic_show">\n                        <p>\n                            <a href="/goods-' + data[i].Goods.id + '.html">') + data[i].Goods.name + '</a>\n                        </p>\n                    </div>\n                    <div class="price">\n                        <span>\uFFE5<span>' + data[i].Goods.goods_price + '</span></span>\n                    </div>\n                </li>';


              };
              $('.drop_shop_car .shop_list').html(html);
              $('.small_shop_price').text(small_price);
            
            }
        });
    };
    //小购车没登录的情况下调用的
    function small_car2(data) {
        var html = "";
        for (var i = 0; i < data.length; i++) {
            if (data[i].id) {
                small_price += parseInt(data[i].goods_price);
                html += '\n                <li class="clearfix">\n                    <div class="shoping_pic">\n                        <a href="/goods-' + data[i].id + '.html"><img src="' + (data[i].GoodsImgs.thumb ? isImgHttp(data[i].GoodsImgs.thumb) : '') + ('" alt=""></a>\n                    </div>\n                    <div class="pic_show">\n                        <p>\n                            <a href="/goods-' + data[i].id + '.html">') + data[i].name + '</a>\n                        </p>\n                    </div>\n                    <div class="price">\n                        <span>\uFFE5<span>' + data[i].goods_price + '</span></span>\n                    </div>\n                </li>';
            }
        };
        $('.drop_shop_car .shop_list').html(html);
        $('.small_shop_price').text(small_price);
    };
    function isUser() {
        var goodsList = JSON.parse(localStorage.getItem('noUsers')) || [];
        if (goodsList.length) {
            $('.drop_shop_car').show();
            $('.no_shop').hide();
            small_car2(goodsList);
        } else {
            return;
        }
    };
});